//
//  SearchViewController.m
//  foodlist
//
//  Created by HappyMilk 02 on 2017/8/16.
//  Copyright © 2017年 tomi. All rights reserved.
//

#import "SearchViewController.h"
#import "MJRequestServer.h"
#import <MJRefresh.h>
#import "FoodModel.h"
#import "MJLocaStorage.h"
#import "LoginHeader.h"
#import "ResultViewController.h"
#import <SVProgressHUD.h>

@interface SearchViewController ()

@property (weak, nonatomic) IBOutlet UITextField *tf_search;

@property (weak, nonatomic) IBOutlet UIView *view_list;

@property (weak, nonatomic) IBOutlet UIView *view_search;

@property (nonatomic ,strong) NSMutableArray *searchArray;

@end

@implementation SearchViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setupListView];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.searchArray = [NSMutableArray array];
    // Do any additional setup after loading the view.
    self.tf_search.layer.masksToBounds = YES;
    self.tf_search.layer.cornerRadius = 8;
    self.view_search.layer.masksToBounds = YES;
    self.view_search.layer.cornerRadius = 8;

    
}
- (IBAction)searchFoodAction:(UIButton *)sender {
    
    if (!(self.tf_search.text.length > 0)) {
        return;
    }
    [self saveSearchText];
    [self getListData];
    
    self.tf_search.text = @"";
    [self.tf_search resignFirstResponder];
}

- (void)getListData{
    
    [SVProgressHUD show];
    [MJRequestServer Post:@{@"keyword":self.tf_search.text,@"num":@"20",@"appkey":@"63a288a68764b5e2"}
                urlString:@"http://api.jisuapi.com/recipe/search"
               andSuccess:^(id sender) {
                   
                   [SVProgressHUD dismiss];
                   if ([sender[@"status"] isEqualToString:@"0"]) {
                       NSArray *arr = [FoodModel mj_objectArrayWithKeyValuesArray:sender[@"result"][@"list"]];
                       if (arr.count>0) {
                           
                           VC_INIT_WITH_STORYBOARD(Main, ResultViewController, vc)
                           vc.listArray = arr;
                           [self.navigationController pushViewController:vc animated:YES];
                       }else{
                           [SVProgressHUD showInfoWithStatus:@"亲，没有这道菜哟"];
                       }
                   }else{
                       [SVProgressHUD showInfoWithStatus:@"亲，没有这道菜哟"];
                   }
               } andFailure:^(id sender) {
                   [SVProgressHUD dismiss];
               }];
}

- (void)saveSearchText{
    
    NSMutableArray *muarr = [[MJLocaStorage getArrayFile:@"SearchList"] mutableCopy];
    [muarr addObject:self.tf_search.text];
    [MJLocaStorage saveArrayFile:[muarr copy] AndFileName:@"SearchList"];
    
    [self setupListView];
}

- (void)setupListView{
    for (UIView *subview in self.view_list.subviews) {
        [subview removeFromSuperview];
    }
    //
    NSMutableArray *muarr = [[MJLocaStorage getArrayFile:@"SearchList"] mutableCopy];
    self.searchArray = muarr;
    //NSArray *arr = @[@"可乐鸡翅",@"可乐",@"可乐鸡",@"可乐",@"鸡翅",@"可乐",@"可乐",@"可乐鸡"];
    
    CGFloat btn_x = 0;
    CGFloat btn_y = 0;
    
    CGFloat number = 0;
    if (muarr.count>20) {
        number = 20;
    }else{
        number = muarr.count;
    }
    for (int i=number-1; i>=0; i--) {
        
        NSString *str = muarr[i];
        CGRect strRect = [str boundingRectWithSize:(CGSize){999,40} options:NSStringDrawingUsesDeviceMetrics attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:18]} context:nil];
        
        if ((strRect.size.width+30) > self.view_list.frame.size.width) {
            strRect = (CGRect){1,1,self.view_list.frame.size.width,1};
        }
        
        if ((btn_x + (strRect.size.width+30)) > self.view_list.frame.size.width) {
            btn_y = btn_y + 50;
            btn_x = 0;
        }
        
        UIButton *btn = [[UIButton alloc] initWithFrame:(CGRect){ btn_x, btn_y, strRect.size.width+20, 40}];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:18]];
        [btn setTitle:str forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        [btn.titleLabel setTextAlignment:NSTextAlignmentCenter];
        [btn addTarget:self action:@selector(historySearchAction:) forControlEvents:UIControlEventTouchUpInside];
        [btn setTag:i];
        [btn setBackgroundColor:HEXCOLOR(0xE5E5E5)];
        btn.layer.masksToBounds = YES;
        btn.layer.cornerRadius = 8;
        [self.view_list addSubview:btn];
        
        btn_x = btn_x + (strRect.size.width+30);
        
    }
}

- (void)historySearchAction:(UIButton *)btn{
    
    NSString *str = [self.searchArray objectAtIndex:btn.tag];
    
    [SVProgressHUD show];
    [MJRequestServer Post:@{@"keyword":str,@"num":@"20",@"appkey":@"63a288a68764b5e2"}
                urlString:@"http://api.jisuapi.com/recipe/search"
               andSuccess:^(id sender) {
                   
                   [SVProgressHUD dismiss];
                   if ([sender[@"status"] isEqualToString:@"0"]) {
                       NSArray *arr = [FoodModel mj_objectArrayWithKeyValuesArray:sender[@"result"][@"list"]];
                       if (arr.count>0) {
                           
                           VC_INIT_WITH_STORYBOARD(Main, ResultViewController, vc)
                           vc.listArray = arr;
                           [self.navigationController pushViewController:vc animated:YES];
                       }else{
                           [SVProgressHUD showInfoWithStatus:@"亲，没有这道菜哟"];
                       }
                   }else{
                       [SVProgressHUD showInfoWithStatus:@"亲，没有这道菜哟"];
                   }
               } andFailure:^(id sender) {
                   [SVProgressHUD dismiss];
               }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
